package com.mx.tool.form.window;

import cn.hutool.core.io.FileUtil;
import com.mx.tool.util.NotifyUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.File;
import java.nio.charset.Charset;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-11 11:37
 * @Description:
 */
public class BjWindow {
    private JPanel jPanel;
    private JEditorPane editorPane;
    private JTextField textField;
    private JButton chooseFileButton;
    private JButton saveButton;
    private File file;

    public JPanel getContent() {
        return jPanel;
    }

    public BjWindow() {
        //保存
        saveButton.addActionListener(e -> {
            if (file == null) {
                NotifyUtil.error("文件选择错误");
                return;
            }
            saveFile();
        });
        //监听ctrl+s保存
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        toolkit.addAWTEventListener(event -> {
            if (event.getClass() == KeyEvent.class) {
                KeyEvent kE = ((KeyEvent) event);
                // 处理按键事件 Ctrl+S
                if (kE.getKeyCode() == KeyEvent.VK_S
                        && kE.isControlDown() && !kE.isAltDown()
                        && kE.getID() == KeyEvent.KEY_PRESSED) {
                    saveFile();
                }
            }

        }, AWTEvent.KEY_EVENT_MASK);
        //选择文件
        chooseFileButton.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(jPanel);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                //得到选择的文件
                file = chooser.getSelectedFile();
                if (file == null || !file.exists()) {
                    NotifyUtil.error("文件选择错误");
                    return;
                }
                textField.setText(file.getAbsolutePath());
                editorPane.setText(getFileContent(file));
            }
        });
    }

    private void saveFile() {
        String text = editorPane.getText();
        FileUtil.writeString(text, file, Charset.defaultCharset());
        NotifyUtil.info("保存成功");
    }

    private String getFileContent(File file) {
        return FileUtil.readString(file, Charset.defaultCharset());
    }
}
